package com.neiquan.neiquandemo.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import com.bumptech.glide.Glide;
import com.neiquan.neiquandemo.appliction.MyApplication;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;

import cn.finalteam.toolsfinal.StringUtils;

public class DonwloadSaveImg {
    public static String cityChangeUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.citychangeimage/";
    public static String startappUrl ="/.startappimage/";

    public static void donwloadImg(final String filePath, final String fileName) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = Glide.with(MyApplication.getInstance().getApplicationContext())
                            .asBitmap()
                            .load(filePath)
                            .into(200, 200)
                            .get();

                    if (bitmap != null)
                        saveFile(bitmap, fileName);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void donwloadBigImg(final String filePath, final String fileName) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(filePath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(input);
                    if (bitmap != null)
                        saveFileBig(bitmap, fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void donwloadCityImg(final String filePath, final String fileName) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(filePath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(input);
                    if (bitmap != null)
                        saveCityFile(bitmap, fileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void donwloadImg(final String filePath, final String fileName, final Context context) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = Glide.with(MyApplication.getInstance().getApplicationContext())
                            .asBitmap()
                            .load(filePath)
                            .into(200, 200)
                            .get();

                    if (bitmap != null)
                        saveFile(bitmap, fileName, context);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 保存图片
     *
     * @param bm
     * @throws IOException
     */

    public static void saveCityFile(Bitmap bm, String fileName) throws IOException {

        File dir = new File(cityChangeUrl);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = dir.getAbsolutePath() + File.separator + fileName;

        File myCaptureFile = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }

    public static void saveFileBig(Bitmap bm, String fileName) throws IOException {

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + startappUrl);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = dir.getAbsolutePath() + File.separator + fileName;

        File myCaptureFile = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }


    public static void saveFile(Bitmap bm, String fileName) throws IOException {

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/.themeimage");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = dir.getAbsolutePath() + File.separator + fileName;

        File myCaptureFile = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }

    public static void saveFile(Bitmap bm, String fileName, final Context context) throws IOException {

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/daliynewsfile");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = dir.getAbsolutePath() + File.separator + fileName;

        File myCaptureFile = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
//        List<String> list = PreferenceHelper.getList("sendfilelist" + LoginKeyUtil.getBizUserId());
//        list.add(fileName + FILETAG + filePath);
//        PreferenceHelper.setList("sendfilelist" + LoginKeyUtil.getBizUserId(), list);
//        String[] imgUrls = new String[1];
//        imgUrls[0] = filePath;
//        Intent intent = new Intent();
//        intent.putExtra("imageUrls", imgUrls);
//        intent.putExtra("curImageUrl", "");
//        intent.setClass(context, PhotoBrowserActivity.class);
//        context.startActivity(intent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            MediaScannerConnection.scanFile(context, new String[]{myCaptureFile.getAbsolutePath()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            mediaScanIntent.setData(uri);
                            context.sendBroadcast(mediaScanIntent);
                        }
                    });
        } else {
            File file1 = new File(filePath);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
        }
    }

    //保存图片并更新图库

    public static String saveFileUp(Bitmap bm, String fileName, Context context) throws IOException {

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/daliynewsfile");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = dir.getAbsolutePath() + File.separator + fileName + ".jpg";

        File myCaptureFile = new File(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
        return filePath;
    }

    public static String saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }

        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
// 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
// 最后通知图库更新
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(file.getPath()))));
        return appDir.getPath()+"/"+fileName;
    }
}
